/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package packForm.Administracao;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import packController.CtrVariaveis;
import packDatabase.DaoAcess;
import packForm.Padroes.FrmPesquisar;

/**
 *
 * @author everaldo
 */
public class FrmCaixa extends javax.swing.JInternalFrame {
    DaoAcess conexao = new DaoAcess();
    /**
     * Creates new form FrmCaixa
     */
    public FrmCaixa() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabFormaPagamento = new javax.swing.JTable();
        txtCodFormaPag = new javax.swing.JTextField();
        btnPesquisarFormaPag = new javax.swing.JButton();
        txtFormaPag = new javax.swing.JTextField();
        btnAdicionar = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabItensPedido = new javax.swing.JTable();
        jLabel8 = new javax.swing.JLabel();
        txtCodPedido = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtCodStatus = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtStatus = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblValorTotal = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtCodMesa = new javax.swing.JTextField();
        txtValorForPag = new javax.swing.JTextField();
        btnRemover = new javax.swing.JButton();
        txtDataAbertura = new javax.swing.JTextField();
        txtDataFechamento = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        btnFecharConta = new javax.swing.JButton();
        btnProcurar = new javax.swing.JButton();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tabFormaPagamento.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Forma Pagamento", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tabFormaPagamento);

        txtCodFormaPag.setEditable(false);

        btnPesquisarFormaPag.setText("...");
        btnPesquisarFormaPag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarFormaPagActionPerformed(evt);
            }
        });

        txtFormaPag.setEditable(false);

        btnAdicionar.setFont(new java.awt.Font("Ubuntu", 0, 9)); // NOI18N
        btnAdicionar.setText("+");
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });

        jLabel9.setText("Formas de pagamento:");

        tabItensPedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Produto", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tabItensPedido);

        jLabel8.setText("Itens consumidos:");

        txtCodPedido.setEditable(false);

        jLabel1.setText("Código Pedido:");

        jLabel2.setText("Código da Mesa:");

        jLabel4.setText("Data Abertura:");

        txtCodStatus.setEditable(false);

        jLabel3.setText("Status:");

        txtStatus.setEditable(false);

        jLabel7.setText("Data Fechamento:");

        jLabel5.setFont(new java.awt.Font("Ubuntu", 1, 45)); // NOI18N
        jLabel5.setText("Valor total:");

        lblValorTotal.setFont(new java.awt.Font("Ubuntu", 1, 45)); // NOI18N
        lblValorTotal.setForeground(new java.awt.Color(0, 85, 255));
        lblValorTotal.setText("0.00");

        jLabel10.setFont(new java.awt.Font("Ubuntu", 1, 45)); // NOI18N
        jLabel10.setForeground(new java.awt.Color(0, 85, 255));
        jLabel10.setText("R$");

        txtCodMesa.setEditable(false);

        txtValorForPag.setEditable(false);

        btnRemover.setFont(new java.awt.Font("Ubuntu", 0, 9)); // NOI18N
        btnRemover.setText("-");
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        txtDataAbertura.setEditable(false);

        txtDataFechamento.setEditable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(txtCodFormaPag, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnPesquisarFormaPag)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFormaPag, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtValorForPag, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel9)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtCodPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(txtCodMesa, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel4)
                                            .addComponent(txtDataAbertura, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtDataFechamento, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jLabel7)))
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addComponent(txtCodStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblValorTotal))
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCodPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCodStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCodMesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDataAbertura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDataFechamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(2, 2, 2))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel10)
                            .addComponent(lblValorTotal))
                        .addGap(11, 11, 11)))
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCodFormaPag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnPesquisarFormaPag)
                            .addComponent(txtFormaPag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtValorForPag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnFecharConta.setText("Fechar a Conta");
        btnFecharConta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharContaActionPerformed(evt);
            }
        });

        btnProcurar.setText("Procurar");
        btnProcurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProcurarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnFecharConta)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnProcurar, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFecharConta)
                    .addComponent(btnProcurar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProcurarActionPerformed
        FrmPesquisar pesquisar = new FrmPesquisar(null,true,"TAB_PEDIDOS.CODPEDIDO AS 'Codigo Pedido', TAB_PEDIDOS.CODMESA AS 'Cod. Mesa', TAB_PEDIDOS.VALORTOTAL AS 'Valor Total', TAB_PEDIDOS.STATUS AS 'Status', TAB_PEDIDOS.DATAABERTURA AS 'Data de Abertura'",
                "TAB_PEDIDOS","INNER JOIN TAB_MESAS ON TAB_MESAS.CODMESA=TAB_PEDIDOS.CODMESA",
                "AND TAB_MESAS.CODEMPRESA="+CtrVariaveis.empresaLogada);
        pesquisar.comboPesquisa.addItem("CodPedido");
        pesquisar.comboPesquisa.addItem("CodMesa");
        pesquisar.comboPesquisa.addItem("ValorTotal");
        pesquisar.comboPesquisa.addItem("Status");
        pesquisar.comboPesquisa.addItem("CodPedido");
        pesquisar.comboPesquisa.addItem("DataAbertura");
        pesquisar.setVisible(true);
        if(!pesquisar.dados.get(3).equals("1")){
            if (pesquisar.dados.get(3).equals("0")){
                btnPesquisarFormaPag.setEnabled(false);
                btnAdicionar.setEnabled(false);
                btnRemover.setEnabled(false);
                txtValorForPag.setEditable(false);
            }else{
                btnPesquisarFormaPag.setEnabled(true);
                btnAdicionar.setEnabled(true);
                btnRemover.setEnabled(true);
                txtValorForPag.setEditable(true);
            }
            if(pesquisar.dados.size()!=0){
                txtDataFechamento.setText(pesquisar.dados.get(5));
                txtCodPedido.setText(pesquisar.dados.get(0));
                txtCodStatus.setText(pesquisar.dados.get(3));
                if(pesquisar.dados.get(3).equals("0")){
                    txtStatus.setText("FECHADO");
                }else if(pesquisar.dados.get(3).equals("1")){
                    txtStatus.setText("ABERTO");
                }else if (pesquisar.dados.get(3).equals("2")){
                    txtStatus.setText("CAIXA");
                }
                txtCodMesa.setText(pesquisar.dados.get(1));
                txtDataAbertura.setText(pesquisar.dados.get(4));
                lblValorTotal.setText(pesquisar.dados.get(2));
                limparTabela(tabItensPedido);
                limparTabela(tabFormaPagamento);
                //CARREGANDO PRODUTOS:
                conexao.OpenConect();
                conexao.Select("SELECT TAB_PEDIDOPRODUTOS.CODPRODUTO, TAB_PRODUTOS.PRODUTO, TAB_PEDIDOPRODUTOS.VALOR FROM TAB_PEDIDOPRODUTOS " +
                                "INNER JOIN TAB_PRODUTOS ON (TAB_PRODUTOS.CODPRODUTO=TAB_PEDIDOPRODUTOS.CODPRODUTO) " +
                                "WHERE CODPEDIDO="+txtCodPedido.getText());
                try {
                    conexao.rs.beforeFirst();
                    DefaultTableModel itensPedido = (DefaultTableModel) tabItensPedido.getModel();
                    while(conexao.rs.next()){
                        itensPedido.addRow(new String [] {conexao.rs.getString("TAB_PEDIDOPRODUTOS.CODPRODUTO"),conexao.rs.getString("TAB_PRODUTOS.PRODUTO"),conexao.rs.getString("TAB_PEDIDOPRODUTOS.VALOR")});
                    }
                } catch (SQLException ex) {
                    System.out.println("Erro: "+ex.getMessage());
                }
                conexao.CloseConect();

                //CARREGANDO AS FORMAS DE PAGAMENTO:
                conexao.OpenConect();
                conexao.Select("SELECT TAB_FINANCEIROITEM.CODFORMAPAGAMENTO,TAB_FORMASPAGAMENTO.FORMAPAGAMENTO,TAB_FINANCEIROITEM.VALOR " +
                                "FROM TAB_FINANCEIROITEM " +
                                "INNER JOIN TAB_FINANCEIRO ON (TAB_FINANCEIRO.CODFINANCEIRO=TAB_FINANCEIROITEM.CODFINANCEIRO) " +
                                "INNER JOIN TAB_FORMASPAGAMENTO ON (TAB_FORMASPAGAMENTO.CODFORMAPAGAMENTO=TAB_FINANCEIROITEM.CODFORMAPAGAMENTO) " +
                                "WHERE TAB_FINANCEIRO.CODPEDIDO="+txtCodPedido.getText());
                try {
                    conexao.rs.beforeFirst();
                    DefaultTableModel formasPag = (DefaultTableModel) tabFormaPagamento.getModel();
                    while(conexao.rs.next()){
                        formasPag.addRow(new String [] {conexao.rs.getString("TAB_FINANCEIROITEM.CODFORMAPAGAMENTO"),conexao.rs.getString("TAB_FORMASPAGAMENTO.FORMAPAGAMENTO"),conexao.rs.getString("TAB_FINANCEIROITEM.VALOR")});
                    }
                } catch (SQLException ex) {
                    System.out.println("Erro: "+ex.getMessage());
                }
                conexao.CloseConect();
            }
        }else{
            JOptionPane.showMessageDialog(null, "Não é possivel alterar pedidos abertos!", "Atenção",0);            
        }
    }//GEN-LAST:event_btnProcurarActionPerformed

    private void btnPesquisarFormaPagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarFormaPagActionPerformed
        FrmPesquisar pesquisar = new FrmPesquisar(null,true,"CODFORMAPAGAMENTO AS 'Código', FORMAPAGAMENTO AS 'Forma de pagamento',CODTIPODEPAGAMENTO AS 'Tipo'","TAB_FORMASPAGAMENTO","","");
        pesquisar.comboPesquisa.addItem("CodFormaPagamento");
        pesquisar.comboPesquisa.addItem("FormaPagamento");
        pesquisar.comboPesquisa.addItem("CodTipoDePagamento");
        pesquisar.setVisible(true);
        if (pesquisar.dados.size()!=0){
            txtCodFormaPag.setText(pesquisar.dados.get(0));
            txtFormaPag.setText(pesquisar.dados.get(2));
        }
    }//GEN-LAST:event_btnPesquisarFormaPagActionPerformed

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        if(!txtCodPedido.getText().equals("")){
            boolean achou=false;
            if (tabFormaPagamento.getRowCount()!=0){
                for (int i=0;i<tabFormaPagamento.getRowCount();i++){
                    if (tabFormaPagamento.getValueAt(i, 0).equals(txtCodFormaPag.getText())){
                        achou=true;
                    }
                }
                if (achou==true){
                    JOptionPane.showMessageDialog(null, "Não é possivel incluir uma forma de pagamento mais de uma vez!", "Atenção!", 0);
                }
            }
            if(achou==false){
                if (!txtValorForPag.getText().equals("")){
                    DefaultTableModel modelo = (DefaultTableModel) tabFormaPagamento.getModel();
                    modelo.addRow(new String [] {txtCodFormaPag.getText(),txtFormaPag.getText(),txtValorForPag.getText()});
                    if (!(txtCodFormaPag.getText().equals(""))){
                            try {
                            conexao.OpenConect();
                            conexao.Insert("INSERT INTO TAB_PEDIDOFORMASPAGAMENTO(CODPEDIDO,CODFORMAPAGAMENTO) VALUES("+txtCodPedido.getText()+","+txtCodFormaPag.getText()+")");
                            conexao.Select("SELECT CODFINANCEIRO FROM TAB_FINANCEIRO WHERE CODPEDIDO="+txtCodPedido.getText());
                            conexao.rs.first();
                            int codFinanceiro=conexao.rs.getInt("CODFINANCEIRO");
                            conexao.Insert("INSERT INTO TAB_FINANCEIROITEM(CODFINANCEIRO,VALOR,CODFORMAPAGAMENTO) VALUES("+codFinanceiro+",'"+txtValorForPag.getText()+"',"+txtCodFormaPag.getText()+")");
                        } catch (SQLException ex) {
                            System.out.println("Erro: "+ex.getMessage());                    
                        }
                        conexao.CloseConect(); 
                    }       
                    txtCodFormaPag.setText("");
                    txtFormaPag.setText("");
                    txtValorForPag.setText("");
                }else{
                JOptionPane.showMessageDialog(null, "Informe o valor da parcela!", "Atenção",0);                
                }
            }
        }else{
            JOptionPane.showMessageDialog(null, "Informe o pedido!", "Atenção",0);
        }
    }//GEN-LAST:event_btnAdicionarActionPerformed

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        if(tabFormaPagamento.getRowCount()!=0){
            if(!txtCodPedido.getText().equals("")){
                conexao.OpenConect();
                int selecao,cod=0;
                selecao=tabFormaPagamento.getSelectedRow();
                conexao.Select("SELECT CODPEDIDOFORMASPAGAMENTO FROM TAB_PEDIDOFORMASPAGAMENTO WHERE CODPEDIDO="+txtCodPedido.getText()+" AND CODFORMAPAGAMENTO="+tabFormaPagamento.getValueAt(selecao, 0));
                try {
                    conexao.rs.first();
                    cod=conexao.rs.getInt("CODPEDIDOFORMASPAGAMENTO");
                } catch (SQLException ex) {
                    System.out.print("Erro: "+ex.getMessage());
                }
                conexao.Delete("DELETE FROM TAB_PEDIDOFORMASPAGAMENTO WHERE CODPEDIDOFORMASPAGAMENTO="+cod);
                conexao.CloseConect();

                try {
                    conexao.OpenConect();
                    conexao.Select("SELECT CODFINANCEIRO FROM TAB_FINANCEIRO WHERE CODPEDIDO="+txtCodPedido.getText());
                    conexao.rs.first();
                    int cod2=conexao.rs.getInt("CODFINANCEIRO");
                    conexao.Delete("DELETE FROM TAB_FINANCEIROITEM WHERE CODFINANCEIRO="+cod2+" AND CODFORMAPAGAMENTO="+tabFormaPagamento.getValueAt(selecao, 0));
                } catch (SQLException ex) {
                    System.out.print("Erro: "+ex.getMessage());
                }
                conexao.CloseConect();
                ((DefaultTableModel) tabFormaPagamento.getModel()).removeRow(tabFormaPagamento.getSelectedRow());
            }else{
                JOptionPane.showMessageDialog(null, "Informe o pedido!", "Atenção",0);            
            }
        }else{
                JOptionPane.showMessageDialog(null, "Não há formas de pagamento para remover!", "Atenção",0);            
        }
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void btnFecharContaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharContaActionPerformed
        double totalItens=0.0;
        if (txtCodPedido.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Informe o pedido!", "Atenção",0);                        
        }else if (txtCodStatus.getText().equals("0")){
            JOptionPane.showMessageDialog(null, "O pedido já foi fechado!", "Atenção",0); 
        }else{
            if (tabFormaPagamento.getRowCount()!=0){
                for(int cont=0;cont<tabFormaPagamento.getRowCount();cont++){
                    totalItens=totalItens+Double.parseDouble(tabFormaPagamento.getValueAt(cont, 2).toString());
                    //System.out.println("Total Parcial"+totalItens);
                }  
                if (totalItens==Double.parseDouble(lblValorTotal.getText())){
                    try{
                        conexao.OpenConect();
                        conexao.Update("UPDATE TAB_PEDIDOS SET STATUS=0, DATAFECHAMENTO=NOW() WHERE CODPEDIDO="+txtCodPedido.getText()+" ");
                        conexao.CloseConect();
                        conexao.OpenConect();
                        conexao.Select("SELECT COUNT(*) AS 'QUANT' FROM TAB_FINANCEIROITEM " +
                                        "INNER JOIN TAB_FINANCEIRO ON (TAB_FINANCEIRO.CODFINANCEIRO=TAB_FINANCEIROITEM.CODFINANCEIRO) " +
                                        "WHERE TAB_FINANCEIRO.CODPEDIDO="+txtCodPedido.getText());
                        conexao.rs.first();
                        int quantParcelas = conexao.rs.getInt("QUANT");
                        conexao.CloseConect();
                        
                        conexao.OpenConect();
                        conexao.Select("SELECT CODFORMAPAGAMENTO FROM TAB_FINANCEIROITEM " +
                                        "INNER JOIN TAB_FINANCEIRO ON (TAB_FINANCEIRO.CODFINANCEIRO=TAB_FINANCEIROITEM.CODFINANCEIRO) " +
                                        "WHERE TAB_FINANCEIRO.CODPEDIDO="+txtCodPedido.getText()+" "+
                                        "LIMIT 1");
                        conexao.rs.first();
                        int codFormaPag = conexao.rs.getInt("CODFORMAPAGAMENTO");
                        conexao.CloseConect();
                        
                        conexao.OpenConect();
                        conexao.Select("SELECT FORMAPAGAMENTO FROM TAB_FORMASPAGAMENTO WHERE CODFORMAPAGAMENTO="+codFormaPag);
                        conexao.rs.first();
                        String formaPagamento= conexao.rs.getString("FORMAPAGAMENTO");
                        conexao.CloseConect();
                        
                        conexao.OpenConect();
                        conexao.Update("UPDATE TAB_FINANCEIRO SET "
                                        + "DATAFECHAMENTO=NOW(),"
                                        + "QUANTPARCELAS="+quantParcelas+","
                                        + "CODFORMAPAGAMENTOPAI="+codFormaPag+","
                                        + "FORMAPAGAMENTO='"+formaPagamento+"' "
                                       + "WHERE TAB_FINANCEIRO.CODPEDIDO="+txtCodPedido.getText());
                        
                        JOptionPane.showMessageDialog(null, "Pagamento Efetuado com sucesso!", "Atenção",1);  
                        limparTela();
                        conexao.CloseConect();
                    }catch(SQLException e){
                        System.out.println("Erro: "+e.getMessage());
                    }
                }else{
                     JOptionPane.showMessageDialog(null, "O valor total das formas de pagamento difere dos somatorio do pedido!", "Atenção",0);                           
                }
            }else{
                JOptionPane.showMessageDialog(null, "Defina as formas de pagamento do pedido!", "Atenção",0);                           
            }
        }  
    }//GEN-LAST:event_btnFecharContaActionPerformed
    
    public void limparTela(){
        txtCodPedido.setText("");
        txtCodStatus.setText("");
        txtStatus.setText("");
        txtCodMesa.setText("");
        txtDataAbertura.setText("");
        txtDataFechamento.setText("");
        lblValorTotal.setText("0.00");
        txtCodFormaPag.setText("");
        txtFormaPag.setText("");
        txtValorForPag.setText("");
        txtValorForPag.setEditable(true);
        btnAdicionar.setEnabled(true);
        btnRemover.setEnabled(true);
        limparTabela(tabFormaPagamento);
        limparTabela(tabItensPedido);
    }
   
    public void limparTabela(javax.swing.JTable tabela){  
        DefaultTableModel modelo = (DefaultTableModel) tabela.getModel(); 
        if(tabela.getRowCount()>0){
            int i=0;
            int contColunas=modelo.getRowCount();
            while(i<contColunas){
                modelo.removeRow(0);
                i++; 
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnFecharConta;
    private javax.swing.JButton btnPesquisarFormaPag;
    private javax.swing.JButton btnProcurar;
    private javax.swing.JButton btnRemover;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblValorTotal;
    private javax.swing.JTable tabFormaPagamento;
    private javax.swing.JTable tabItensPedido;
    private javax.swing.JTextField txtCodFormaPag;
    private javax.swing.JTextField txtCodMesa;
    private javax.swing.JTextField txtCodPedido;
    private javax.swing.JTextField txtCodStatus;
    private javax.swing.JTextField txtDataAbertura;
    private javax.swing.JTextField txtDataFechamento;
    private javax.swing.JTextField txtFormaPag;
    private javax.swing.JTextField txtStatus;
    private javax.swing.JTextField txtValorForPag;
    // End of variables declaration//GEN-END:variables
}
